package com.demo.io;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author jasper
 */
@Slf4j
public class ReadImage2Byte {
    public static byte[] readImage2ByteArray(String path) {
        File f = new File(path);
        BufferedImage bi;
        byte[] bytes = null;
        try {
            bi = ImageIO.read(f);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bi, "jpg", baos);
            bytes = baos.toByteArray();
        } catch (Exception e) {
            log.error("read image error: {}", e);
        }
        return bytes;
    }

    public static byte[] readUrl2ByteArray(String url) {
        byte[] data = null;
        try {
            URL ul = new URL(url);
            InputStream inputStream = ul.openStream();
            data = new byte[inputStream.available()];

            int read = inputStream.read(data);
            log.info("read = {}", read);
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] encode = Base64Utils.encode(data);
        //返回Base64编码过的字节数组字符串

        return encode;
    }
}
